<?php

namespace app\common\business;

use app\common\lib\Str;
use app\common\lib\Time;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class ScreenUser{

    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\ScreenUser();
    }

    /**
     * @throws Exception
     */
    public function login($data){
        try {
            $user = self::getScreenUserByUserName($data['username']);
            if (empty($user)){
                throw new Exception("该用户不存在");
            }
            //判断密码是否正确
            if ($user['password'] != Str::getUserPassword($data['password'])) {
                throw new Exception("密码错误");
            }

            //需要记录信息到mysql表中
            $updateData = [
                "last_login_time" => time(),
                "last_login_ip" => request()->ip()
            ];
            $res = $this->model->updateById($user['id'], $updateData);
            if (!$res) {
                throw new Exception("登录失败");
            }
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }

        $token = Str::getLoginToken($data['username']);
        $redisData = [
            "id" => $user['id'],
            "username" => $data['username'],
        ];

        $res = cache(config("redis.token_pre") . $token, $redisData, Time::userLoginExpiresTime(1));//过期时间 1：7天 2：30天

        return $res ? ["token" => $token, "username" => $data['username']] : false;
    }

    /**
     * 通过用户名获取用户数据
     * @param $username
     * @return array|false
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getScreenUserByUserName($username){
        $adminUser = $this->model->getScreenUserByUserName($username);
        if (empty($adminUser) || $adminUser->status != config("status.mysql.table_normal")) {
            return false;
        }
        return $adminUser->toArray();
    }

}
